<?php
/* 图片相关操作控制器 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class FileController extends HomeController
{
    //文件上传
    public function upload(Request $request) {
        try {
            //接受参数
            $file = $request->file('file');
            //判断是否有文件上传
            if (!$file) {
                return response()->json(['code' => HTTP_ERROR,'message' => '请选择文件']);
            }
            //判断文件类型
            if (!$file->isValid()) {
                return response()->json([
                    'code' => HTTP_ERROR,
                    'message' => '文件上传失败',
                    'data' => null
                ]);
            }
            
            //拼接文件路径
            $path = date('Ymd');
            //判断目录是否存在
            if (!is_dir($path)) {
                //创建目录
                mkdir($path, 0755, true);
            }
            $name = $file->getClientOriginalName();

            // 生成唯一文件名，避免文件名冲突
            $fileName = uniqid() . '.' . $file->getClientOriginalExtension();
            $path = $file->storeAs($path, $fileName);
            //拼接文件url，供外界展示
            $url =  Storage::url($path);

            //返回文件路径
            return response()->json([
                'code' => HTTP_OK,
                'message' => '文件上传成功',
                'data' => ['url' => $url, 'path' => $path,'name' => $name], //返回的path路径用于删除文件
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('文件上传失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '文件上传失败',
                'data' => null
            ]);
        }
    }


    //文件删除
    public function delete(Request $request) {
        try {
            //接受参数
            $path = $request->input('path');
            //判断文件是否存在
            /* if (!file_exists($path)) {
                return response()->json(['code' => HTTP_ERROR,'message' => '文件不存在']);
            } */
            //删除文件
            //unlink($path);
            Storage::delete($path);
            return response()->json(['code' => HTTP_OK,'message' => '文件删除成功']);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('文件删除失败: ' . $e->getMessage());
        }
    }



}
